import React, {useEffect, useState} from 'react'
import {Card, Empty, Spin} from 'antd'
import type {CatalogVo, DataSourceTreeNode} from '@/types/source'
import {sourceApi} from '@/services/api/source'

interface Props {
  selectedNode?: DataSourceTreeNode
}

export default function DetailPanel({ selectedNode }: Props) {
  const [loading, setLoading] = useState(false)
  const [catalog, setCatalog] = useState<CatalogVo | null>(null)

  useEffect(() => {
    const t = selectedNode?.nodeType || selectedNode?.type
    if (!selectedNode) {
      setCatalog(null)
      return
    }
    if (t === 'CATALOG') {
      setLoading(true)
      sourceApi
        .getCatalog(selectedNode.name)
        .then((data) => setCatalog(data))
        .catch((e) => console.error(e))
        .finally(() => setLoading(false))
    } else {
      setCatalog(null)
    }
  }, [selectedNode])

  const t = selectedNode?.nodeType || selectedNode?.type
  if (!selectedNode) {
    return (
      <Card title="📊 节点详情" size="small">
        <Empty description="请选择左侧树中的一个节点" />
      </Card>
    )
  }

  if (loading) {
    return (
      <Card title="📊 节点详情" size="small">
        <Spin />
      </Card>
    )
  }

  if (t !== 'CATALOG') {
    return (
      <div style={{ display: 'grid', gap: 12 }}>
        <Card title="📊 节点详情" size="small">
          <div>名称: {selectedNode.name}</div>
          <div>类型: {t}</div>
        </Card>
      </div>
    )
  }

  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <Card title="📊 节点详情" size="small">
        <div>名称: {catalog?.catalogName}</div>
        <div>类型: CATALOG</div>
        <div>主机: {catalog?.host}</div>
        <div>端口: {catalog?.port}</div>
        <div>数据库: {catalog?.databaseType}</div>
        <div>版本: {catalog?.databaseVersion || '-'}</div>
        <div>Doris Catalog: {catalog?.dorisCatalogName}</div>
        <div>系统编码: {catalog?.defaultSystemCode}</div>
      </Card>
      <Card title="🔗 连接状态" size="small">
        <div>服务器: {catalog?.serverConnected ? '✅ 已连接' : '❌ 未连接'} {catalog?.serverConnectedDt ? `(${catalog?.serverConnectedDt})` : ''}</div>
        <div>JDBC: {catalog?.jdbcConnected ? '✅ 已连接' : '❌ 未连接'} {catalog?.jdbcConnectedDt ? `(${catalog?.jdbcConnectedDt})` : ''}</div>
        <div>Doris: {catalog?.dorisConnected ? '✅ 已连接' : '❌ 未连接'} {catalog?.dorisConnectedDt ? `(${catalog?.dorisConnectedDt})` : ''}</div>
      </Card>
    </div>
  )
}